package com.pet_service.config;

import com.pet_service.enums.TUserStatus;
import com.pet_service.mapper.UserMapper;
import com.pet_service.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.springframework.security.core.userdetails.User.withUsername;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-09-20 10:51
 */
//用于用户认证的服务类
@Slf4j
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;
    // UserDetails 接口
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.去mysql数据库中查询用户信息
        com.pet_service.entity.User sysUser = userMapper.selectByUsername(username);
        log.info("当前用户信息:{}",sysUser);
        if(Objects.isNull(sysUser)){
            throw new UsernameNotFoundException("账户不存在!");
        }else if(TUserStatus.DISABLED ==sysUser.getStatus()){ // status 0 封禁  1 正常
            throw new LockedException("账号被锁定,请联系超级管理员!");
        }

        //给这个用户授予权限
        Integer userId = sysUser.getId();
        List<GrantedAuthority> grantedAuthorities = getSysUserAuthority(userId);
        User.UserBuilder userBuilder = withUsername(sysUser.getUsername()); //设置用户名
        userBuilder.password(sysUser.getPassword());//设置密码
        userBuilder.authorities(grantedAuthorities); //设置这个用户拥有的权限
        return userBuilder.build();
    }




    /**
     * 根据用户id获取这个用户具有的权限
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getSysUserAuthority(Integer userId){
        List<GrantedAuthority> list = new ArrayList<>();
        return  list;
    }
}
